package pl.com.like.sequoia.biojava.util.impl;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.com.like.sequoia.biojava.util.IDirHelper;
import pl.com.like.sequoia.exceptions.LogicalException;
import pl.com.like.sequoia.model.bio.enums.FileTypeEnum;

public class DirHelper extends AbstractHelper implements IDirHelper {

	private final static Logger log = LoggerFactory.getLogger(DirHelper.class);

	/**
	 * {@inheritDoc}
	 */
	public File createDestFile(String name, FileTypeEnum fileType) throws LogicalException {
		String path = getFilePath(name, fileType);
		File dirFile = new File(path);
		dirFile.mkdirs();
		File destFile = new File(dirFile, name);
		try {
			destFile.createNewFile();
		} catch (IOException e) {
			throw new LogicalException(MessageFormat.format("Could not create new file {0} in {1}", name, dirFile
					.getAbsoluteFile()), e);
		}
		return destFile;
	}

	/**
	 * create directory tree for downloaded file.
	 * 
	 * @param name
	 * @return
	 */
	public String extendDir(final String name) {
		String tempName = name.trim();
		int dotPos = tempName.lastIndexOf('.');
		String tempString = tempName;
		if (dotPos > 0) {
			tempString = tempName.substring(0, dotPos);
		}
		tempString = tempString.replace('.', '_');
		String separator = getSysSep();
		String outPath = "";
		String regex = ("\\w");
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(tempString);
		StringBuilder a = new StringBuilder(outPath);
		while (m.find()) {
			a.append(m.group());
			a.append(separator);
		}
		return a.toString();
	}

	public String getFilePath(String name, FileTypeEnum fileType) throws LogicalException {
		String filePath = configService.getBasePath();
		if (null == filePath) {
			log.warn("system config base path is not set!");
		}
		String slash = getSysSep();
		filePath += slash;
		switch (fileType) {
			case FASTA:
				filePath += "fasta";
				break;
			case GENBANK:
				filePath += "genbank";
				break;
			case GENPEPT:
				filePath += "genpept";
				break;
			default:
				filePath += "pdb";
		}
		filePath += slash;
		filePath += extendDir(name);
		return filePath;
	}

	/** {@inheritDoc} */
	public String getSysSep() {
		return System.getProperty("file.separator");
	}

}
